package class1;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询所有班级
 */
@WebServlet("/class1/name")
public class ClassNameServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String DBDRIVER = "com.mysql.cj.jdbc.Driver";
        String DBURL = "jdbc:mysql://localhost:3307/javatest";
        String DBUSER = "root";
        String DBPASS = "111111";

        try {
            Connection conn = null;
            Class.forName(DBDRIVER);
            conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
            String sql = "select classId,name from t_class ";
            PreparedStatement pre = conn.prepareStatement(sql);
            ResultSet rs = pre.executeQuery();
            List<ClassNameList> classNameList2 = new ArrayList<>();
            while (rs.next()){
                ClassNameList classNameList = new ClassNameList();
                classNameList.setClassId(rs.getInt("classId"));
                classNameList.setName(rs.getString("name"));
                classNameList2.add(classNameList);
            }
            ClassNameView classNameView = new ClassNameView();
            classNameView.setCode(0);
            classNameView.setData(classNameList2);
            classNameView.setMsg("success");
            ObjectMapper objectMapper = new ObjectMapper();
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write(objectMapper.writeValueAsString(classNameView));
            conn.close();//关闭数据库
            pre.close();
            rs.close();


        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
